//
//  LXRecommendTableViewController.m
//  cat
//
//  Created by imera on 16/1/15.
//  Copyright © 2016年 LX. All rights reserved.
//

#import "LXRecommendTableViewController.h"
#import "SlideBarCell.h"
#import "LXMovieGroupTitleView.h"
#import "LXSliderView.h"
#import "AFNetworking.h"
#import "MBProgressHUD+MJ.h"
#import "LXVideo.h"

#define LXRecommendTableViewControllerSectionHeaderHeight 180

@interface LXRecommendTableViewController ()
/** 栏目头标题图标 */
@property (nonatomic, strong) NSArray *titleIconArray;
/** 轮播指示器 */
@property (nonatomic, weak) UIPageControl *pageControl;
/** 模型数据 */
@property (nonatomic, strong) NSMutableDictionary *videoDict;
/** 轮播模型数据 */
@property (nonatomic, strong) NSArray *sliderVideoArr;
@end

@implementation LXRecommendTableViewController

- (NSMutableDictionary *)videoDict
{
    if (_videoDict == nil) {
        _videoDict = [NSMutableDictionary dictionary];
    }
    return _videoDict;
}

- (NSArray *)titleIconArray
{
    if (_titleIconArray == nil) {
        _titleIconArray = @[@"cat_1",@"cat_2",@"cat_3",@"cat_4",@"cat_5",@"cat_6",@"cat_7",@"cat_8",@"cat_9",@"cat_10",@"cat_11",@"cat_12"];
    }
    return _titleIconArray;
}

- (void)viewDidLoad
{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //获取视频数据
    [self getData];
}


#pragma mark - 获取数据
- (void)getData
{
    //获取数据
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    NSString *url = @"http://cat666.com/cat666-interface/index.php/index/getRecommend";
    
    [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation * operation, id response) {
        //字典转模型
        NSDictionary *dict = response;
        
        //缓存数据
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [path stringByAppendingPathComponent:@"Recommend.plist"];
        
        [dict writeToFile:filePath atomically:YES];
        
        [self dictToModel:dict];
        
    } failure:^(AFHTTPRequestOperation * operation, NSError * error) {
        [MBProgressHUD showError:@"您的网络开小差了..."];
        
        //缓存数据
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filePath = [path stringByAppendingPathComponent:@"Recommend.plist"];
        
        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
        
        [self dictToModel:dict];
        
    }];
}

- (void)dictToModel:(NSDictionary *)dict
{
    NSArray *allKeys = dict.allKeys;
    for (NSString *str in allKeys) {
        NSArray *arr = dict[str];
        if (arr.count == 4) {
            NSMutableArray *videos = [NSMutableArray array];
            for (NSDictionary *dict in arr) {
                LXVideo *video = [[LXVideo alloc]initWithDict:dict];
                [videos addObject:video];
            }
            
            if ([str isEqualToString:@"!@#$%^&*0!@#$%^&*"]) { //轮播数据
                self.sliderVideoArr = videos;
            }else {  //cell数据
                [self.videoDict setValue:videos forKey:[str stringByReplacingOccurrencesOfString:@"!@#$%^&*" withString:@""]];
            }
        }
    }
    [self.tableView reloadData];
}

#pragma mark tableView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.videoDict.count != 0) {
        return self.videoDict.count;
    }
    return 0;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 180;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return LXRecommendTableViewControllerSectionHeaderHeight;
    }
    return 30;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, LXRecommendTableViewControllerSectionHeaderHeight)];
    CGFloat sliderViewH = 0;
    if (section == 0) {
        //添加轮播图
        LXSliderView *sliderView = [[LXSliderView alloc] initWithFirstImage:@"slider1" imageCount:(int)self.sliderVideoArr.count];
        CGFloat sliderViewX = 10;
        CGFloat sliderViewY = 0;
        CGFloat sliderViewW = self.view.frame.size.width - sliderViewX * 2;
        sliderViewH = 150;
        sliderView.frame = CGRectMake(sliderViewX, sliderViewY, sliderViewW, sliderViewH);
        sliderView.delegate = self;
        
        //添加模型数据
        if (self.sliderVideoArr.count != 0) {
            sliderView.videoArr = self.sliderVideoArr;
        }
        
        self.pageControl = sliderView.pageControl;
        [headerView addSubview:sliderView];
        [headerView addSubview:sliderView.pageControl]; //添加pagecontrol
    }
    
    //添加头部标题
    NSArray *titArr = self.videoDict.allKeys;
    UIView *view =[LXMovieGroupTitleView initWithTitle:titArr[section]];
    view.frame = CGRectMake(0, sliderViewH, self.view.frame.size.width, 30);
    [headerView addSubview:view];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 5)];
    footerView.backgroundColor =  LXTableViewCellSeparateColor;
    return footerView;
}

- (SlideBarCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"Cell";
    
    SlideBarCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[SlideBarCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    //给cell赋值数据
    if (self.videoDict.allValues.count != 0) {
        NSArray *videoArr = self.videoDict.allValues[indexPath.section];
        NSArray *videos = [NSArray arrayWithObjects:videoArr[indexPath.row * 2], videoArr[indexPath.row * 2 + 1], nil];
        cell.videos = videos;
    }
    
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    /*** tableview顶部不悬停 */
    CGFloat sectionHeaderHeight = LXRecommendTableViewControllerSectionHeaderHeight;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight){
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
    int currentPage = (scrollView.contentOffset.x / scrollView.frame.size.width) + 0.5;
    self.pageControl.currentPage = currentPage;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

@end
